<template>
  <span>
    <el-input class="form-content" :style="{ width: `${width}px` }" v-model="keyWorld" v-popover:popover
      @focus="show = true" @blur="show = false" :placeholder="placeholder" :disabled="disabled"
      @keyup.native="remoteMethod"></el-input>
    <el-popover v-model="showPopover" popper-class="edit-card-info" ref="popover" placement="bottom-start" title=""
      :width="width" trigger="manual">
      <div class="search-wrap" v-loading="queryLoading">
        <div class="search-item" @click="update(item)" v-for="item in patientList" :key="item.id">姓名:{{
          item.patientName
        }}&emsp;--&emsp;患者id:{{ item.id }}&emsp;--&emsp;性别:{{ item.genderName }}&emsp;--&emsp;年龄:{{ item.age
          }}{{
            ageUnitCodeMap[item.ageUnitCode] | getText }}
        </div>
      </div>
    </el-popover>
  </span>
</template>

<script>
import { findPatientByName } from '@/api/record';
import { getExactType } from '@/utils';
import { ageUnitCodeMap } from '@/utils/enum';
import { debounce } from 'lodash';

export default {
  name: "PatientInput",
  props: {
    value: {
      type: String,
      default: ""
    },
    width: {
      type: String,
      default: "350"
    },
    placeholder: {
      type: String,
      default: "请输入患者姓名/ID"
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: "value",
    event: "input"
  },
  data() {
    return {
      queryLoading: false,
      show: false,
      world: '',
      patientList: [],
      ageUnitCodeMap,
    }
  },
  filters: {
    getText(value) {
      let type = getExactType(value);
      return ['null', 'undefined'].includes(type) ? '-' : value;
    },
  },
  computed: {
    keyWorld: {
      set(val) {
        this.world = val;
        this.$emit('input', val);
      },
      get() {
        return this.value || this.world;
      }
    },
    showPopover: {
      set(val) {
        // this.show = val;
      },
      get() {
        return this.show && this.patientList.length > 0;
      },
    },
  },
  methods: {
    clear() {
      this.world = '';
      this.patientList = [];
      this.$emit('input', this.world);
    },
    update(item) {
      this.world = item.patientName;
      this.$emit('input', this.world);
      this.$emit('update:item', item)
    },
    remoteMethod: debounce(async function (event) {
      let query = event.target.value

      if (query != '') {
        this.queryLoading = true;
        const { data } = await findPatientByName({ keyword: query }).catch(err => { this.queryLoading = false; });
        this.queryLoading = false;
        this.patientList = data || []
      } else {
        this.patientList = [];
      }
    }, 300),
  }
}
</script>

<style lang="scss" scoped>
.form-content.error {
  border: 1px solid red;
  border-radius: 4px;
}
</style>
